package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by xiebang
 * Description  功能
 * //    1.新增用户信息
 * //    2.删除用户信息
 * //    3.修改用户信息
// //实现查找功能
 * User:小谢
 * Date:2022-03-10
 * Time:16:51
 */
//针对 user 表进行增删改查的操作
public class UserDao {
//1.根据用户id来查找 ,根据博客表中的userId来找到作者的详细信息
    public User selectById(int userId){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "select * from user where userId = ?";
            statement = connection.prepareStatement(sql);
            statement.setInt(1,userId);
            resultSet =  statement.executeQuery();
            if (resultSet.next()){
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
            return  null;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
          DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }
//    2.根据用户名来查找(在登录的时候,就需要根据用户名来找到用户密码,进一步进行校验匹配)

    public User selectByName(String name){
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;

        try {
            connection = DBUtil.getConnection();
            String sql = "select * from user where username = ?";
            statement = connection.prepareStatement(sql);
            statement.setString(1,name);
            resultSet =  statement.executeQuery();
            if (resultSet.next()){
                User user = new User();
                user.setUserId(resultSet.getInt("userId"));
                user.setUsername(resultSet.getString("username"));
                user.setPassword(resultSet.getString("password"));
                return user;
            }
            return  null;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(connection,statement,resultSet);
        }
        return null;
    }


    public static void main(String[] args) {
        //测试按id查找
        UserDao userDao = new UserDao();
        User user = new User();
        user = userDao.selectById(1);
//        user = userDao.selectByName("admin");
        System.out.println(user);
    }
}

